import commonConstants from "@/common/commonConstants";
import commonMethod from "@/common/commonMethod";
import RightMenu from "@/common/rightMenu";
import { CallbackProperty, Color, ColorMaterialProperty, defined, HeightReference, ScreenSpaceEventHandler, ScreenSpaceEventType } from "cesium";
import { Track } from "./trackManager";

class NormalTrackListencer{
    constructor(v){
        this.curViewer = v;      
        this.scene = v.scene;
        this.clock = v.clock;
        this.canvas = v.scene.canvas;
        this.camera = v.scene.camera;
        this.ellipsoid = v.scene.globe.ellipsoid;
        
        this.pickEntity = undefined;
        this.tempEntity = undefined;
        this.controlPoint = undefined;
        //控制点集合
        this.controllerPoints = undefined;
        this.drawHandler = null;
        this.params = undefined; 
        this.isActive = false;
        this.isEdit = false;
        this.monitorKey = commonConstants.monitorKey.track;
        this.positions = undefined;
        this.rightmenu = undefined;
        this.isOneTargger = false;//这个是判断修改时的问题，他有一个初次触发，不需要事件
    
        this.callbackFunction = undefined;
        this.trackManager = undefined;
        this.monitorManager = undefined
    }

    setEdit(bool){
        let _this = this;
        _this.isEdit = bool;
    }
    setParams(params){
        let _this = this;
        _this.params = params;
    }
    setTrackManager(trackManager){
        let _this = this;
        _this.trackManager =trackManager;
    }
    setManager(manager){
        this.monitorManager = manager;
    }
    setActive(bool){
        let _this = this;
        _this.isActive = bool;
    }
    setTrackCallback(callback){
        let _this =this;
        _this.callbackFunction = callback;
    }
    /** 
     * 这是开始标绘普通航迹
     */
    deploy () {
        let _this = this;

        _this.positions = [];
        let tempFirst =null;
        if (!_this.drawHandler) {
            _this.drawHandler = new ScreenSpaceEventHandler(_this.canvas);

            _this.drawHandler.setInputAction((event) => {

                if (!_this.isActive) {
                    return;
                }

                let p = commonMethod.judgeClickPosition(event.position,_this.curViewer);
                if (!p) {
                    return;
                }

                _this.destoryRightMenu();
                let cartesian = _this.scene.globe.pick(p.ray, _this.scene);

                if (!defined(cartesian)) {
                    return;
                }

                if (_this.isEdit) {
                    //有控制点
                    if (_this.controlPoint) {
                        _this.controlPoint = undefined;
                        return;
                    }
                    //获得是否有点击到控制点，如果有，则改变，如果没有，就不管
                    if (!_this.controllerPoints) {
                        return;
                    }
                   const ent = commonMethod.judgeClickEntity(_this.curViewer, p.pos);
                    if (!ent) {
                        return;
                    } else {
                         _this.controlPoint = commonMethod.findElementFromArray(_this.controllerPoints,n=>n.id == ent.id);
                    }
                    return;
                }

                if (_this.positions.length < 1) {
                    tempFirst = _this._createPoint(cartesian);
                    _this.positions.push(cartesian);
                    _this.createTempTrack();
                }
                _this.positions.push(cartesian);
            }, ScreenSpaceEventType.LEFT_CLICK);

            _this.drawHandler.setInputAction(function (event) {

                if (!_this.isActive) {
                    return;
                }

                if (!_this.isEdit) {
                    if (!tempFirst) {
                        return;
                    }
                } else {
                    if (!_this.controlPoint) {
                        return;
                    }
                }

                _this.destoryRightMenu();
                let judgeClickPosition = commonMethod.judgeClickPosition(event.endPosition,_this.curViewer);
                if (!judgeClickPosition) {
                    return;
                }
                let cartesian = _this.scene.globe.pick(judgeClickPosition.ray, _this.scene);

                if (!defined(cartesian)) {
                    return;
                }
                if (_this.isEdit) {
                    //通过控制点，修改标绘的点的位置
                    let track = _this.trackManager.getTrackById(_this.pickEntity.id);
                    track.changePosition(_this.controlPoint, cartesian);
                } else {
                    //暂时的线要进行变化
                    tempFirst.position.setValue(cartesian);
                    _this.positions.pop();
                    _this.positions.push(cartesian);
                }

            }, ScreenSpaceEventType.MOUSE_MOVE);

            _this.drawHandler.setInputAction(function (event) {

                if (!_this.isActive) {
                    return;
                }

                let judgeClickPosition = commonMethod.judgeClickPosition(event.position,_this.curViewer);
                if (!judgeClickPosition) {
                    return;
                }

                if (_this.isEdit) {
                    //并不考虑它是否是存在实体，直接结束
                    _this.isEdit = false;
                    _this.controlPoint = undefined;
                    //控制点隐藏
                    _this.setControlPointShow(false);
                    _this.controllerPoints = undefined;

                    // if (_this.callbackFunction){
                    //     _this.callbackFunction()
                    // }

                } else {
                    //表示结束描点，生成航迹
                    if (_this.positions.length < 2) {
                        return;
                    }

                    let track = _this.createTrack(_this.positions);
                    if (_this.callbackFunction) {
                        _this.callbackFunction(track);
                    }

                    _this.curViewer.entities.remove(_this.tempEntity);
                    _this.curViewer.entities.remove(tempFirst);
                    _this.tempEntity = null;
                    _this.positions = [];
                    tempFirst = null;
                }
                _this.monitorManager.deployDefaultMonitor();
            }, ScreenSpaceEventType.RIGHT_CLICK);
        }
    }
    /**
     * 创建一个点对象
     * @param cartesian
     * @return {*}
     * @private
     */
    _createPoint(cartesian){
        let _this=this;
        return _this.curViewer.entities.add({
            position: cartesian,
            point: {
                color: Color.RED,
                pixelSize: 5,
                heightReference: HeightReference.CLAMP_TO_GROUND
            }
        });
    }
    /**
     * 创建临时的航迹线
     * @param cartesian 位置
     */
    createTempTrack(){
        let _this = this;
        let positions = new CallbackProperty( ()=>{
            return _this.positions;
        },false);
        _this.tempEntity = _this.curViewer.entities.add({
            polyline : {
                material:new ColorMaterialProperty(Color.YELLOW),
                positions : positions,
                clampToGround : true,
                width : 3
            }
        });
    }
    /**
     *
     * @param positions {[]}
     * @return {Track}
     */
    createTrack(positions){
        let _this = this;

        let track = new Track(_this.params);
        track.setPositions(positions);

        for (let i = 0; i < positions.length; i++) {
            let createPoint = _this._createPoint(positions[i]);
            createPoint.show = false;
            track.addControlPoint(createPoint);
        }

        let dyPos = new CallbackProperty( ()=>{
            return track.getPositions();
        },false);

        let shape = _this.curViewer.entities.add({
            id:track.getTrackId(),
            polyline : {
                material:new ColorMaterialProperty(Color.YELLOW),
                positions : dyPos,
                clampToGround : true,
                width : 3
            }
        });

        shape.monitorKey = _this.monitorKey;
        shape.entityType = commonConstants.entityType.track;

        track.setTrackEntity(shape);

        _this.monitorManager.getDefaultMonitor().putEntity(shape);

        return track;
    }

    destoryRightMenu(){
        let _this = this;
        if (_this.rightmenu){
            _this.rightmenu.destroy();
            _this.rightmenu = null;
            _this.monitorManager.getDefaultMonitor().setCurRigthMenu(undefined);
        }
    }
    showRightMenuEntity(event,entity) {
        let _this = this;
        _this.destoryRightMenu();
        _this.rightmenu = new RightMenu([{
            itemName: "删除",
            icon: "layui-icon layui-icon-delete",
            callback: function () {
                // 如果删除，表示删除航迹，如果是演员成员，就删除演员
                _this.trackManager.removeTrackById(entity.id);
            }
        }],_this.curViewer);
        _this.rightmenu.show(event,true);
        _this.monitorManager.getDefaultMonitor().setCurRigthMenu(_this.rightmenu);
    }
    /**
     * 处理默认监听带来的事件
     */
    handerEvent(event,pickEntity,clickType) {
        let _this = this;
        _this.pickEntity = pickEntity;

        if (clickType === ScreenSpaceEventType.RIGHT_CLICK){
            //右键菜单
            _this.showRightMenuEntity(event,pickEntity);
        }else if (clickType === ScreenSpaceEventType.LEFT_CLICK){
            _this.controllerPoints = _this.trackManager.getTrackById(pickEntity.id).getControlPoints();
            _this.setControlPointShow(true);
            _this.isEdit = true;
            _this.isActive = true;
        }
    }
    setControlPointShow(bool){
        let _this = this;
        for (let cp of _this.controllerPoints){
            cp.show= bool;
        }
    }
}
export default NormalTrackListencer;